package plutuscat.shishicai.dao;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Consumer;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import plutuscat.shishicai.common.HistoryLotteryDataProvider;
import plutuscat.shishicai.common.NowadayLotteryDataProvider;
import plutuscat.shishicai.domain.Lottery;
import plutuscat.shishicai.util.MyDateUtil;

/**
*
* @author dw_chenqi
* @date 2016年5月3日下午1:28:53
*/
@Repository
public class LotteryDao {

	private static final Logger log = LoggerFactory.getLogger(LotteryDao.class);

	@Autowired
	private JdbcTemplate jt;
	@Autowired
	private NamedParameterJdbcTemplate namedJt;
	@Autowired
	private HistoryLotteryDataProvider historyLotteryDataProvider;
	@Autowired
	private NowadayLotteryDataProvider nowadayLotteryDataProvider;

	public Set<Lottery> pullHistoryLotteryData() {
		return historyLotteryDataProvider.provideDataWithLotteryTimeAsc();
	}

	public Set<Lottery> pullLotteryData(String date) {
		return nowadayLotteryDataProvider.provideDataWithLotteryTimeAsc(date);
	}

	public List<String> getSyncDates() {
		String sql = "select dt from ( select dt,count(*)  ct from t_shishicai where lotteryTime>? group by dt ) t where t.ct<120 ";
		//同步最近30天没有彩票数据的日期
		String startLotteryTime = DateFormatUtils.format(DateUtils.addDays(new Date(), -30), "yyyyMMdd");
		List<String> dates = jt.queryForList(sql, String.class, startLotteryTime);
		/*String maxDateInDates = null;
		if (CollectionUtils.isEmpty(dates)) {
			sql = "select max(dt) from t_shishicai";
			maxDateInDates = jt.queryForObject(sql, String.class);
			if (StringUtils.isBlank(maxDateInDates)) {
				maxDateInDates = DateFormatUtils.format(DateUtils.addDays(new Date(), -31), "yyyy-MM-dd");
			}
		} else {
			maxDateInDates = new TreeSet<String>(dates).last();
		}
		//表中最大日期小于当前日期的情况
		try {
			Date maxDate = DateUtils.parseDate(maxDateInDates, "yyyy-MM-dd");
			int diff = MyDateUtil.diffDay(maxDate, new Date());
			for (int i = 0; diff > 0 && i < diff; i++) {
				dates.add(DateFormatUtils.format(DateUtils.addDays(maxDate, (i + 1)), "yyyy-MM-dd"));
			}
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}*/

		return CollectionUtils.isEmpty(dates) ? Collections.EMPTY_LIST : dates;
	}

	public String getMaxDate() {
		String sql = "select max(dt) from t_shishicai";
		return jt.queryForObject(sql, String.class);
	}

	public void batchAdd(List<Lottery> lotterys) {
		log.info("批量增加彩票数据,总条数:{}", lotterys.size());
		if (CollectionUtils.isEmpty(lotterys)) {
			log.warn("lottery collection is empty!skip it!");
			return;
		}
		int batchSize = 1000;
		int step = (lotterys.size() - 1) / batchSize + 1;
		for (int i = 0; i < step; i++) {
			int endIndex = Math.min(lotterys.size(), (i + 1) * batchSize);

			doBatchAdd(lotterys.subList(i * batchSize, endIndex));
		}
	}

	private void doBatchAdd(List<Lottery> subList) {
		final StringBuilder sql = new StringBuilder();
		sql.append("insert ignore into t_shishicai (lotteryTime, dt, times, winNumbers, w, q, b, s, g,daxiao,danshuang,addTime) values ");
		//(?, ?, ?, ?,?, ?, ?, ?, ?,?)
		final List<Object> args = new ArrayList<Object>();
		subList.forEach(new Consumer<Lottery>() {

			@Override
			public void accept(Lottery t) {
				sql.append("(?, ?, ?, ?,?, ?, ?, ?,?,?,?,?)").append(",");
				args.add(t.getLotteryTime());
				args.add(t.getDt());
				args.add(t.getTimes());
				args.add(t.getWinNumbers());
				args.add(t.getW());
				args.add(t.getQ());
				args.add(t.getB());
				args.add(t.getS());
				args.add(t.getG());
				args.add(t.getDaxiao().value());
				args.add(t.getDanshuang().value());
				args.add(t.getAddTime());
			}
		});
		if (subList.size() > 0) {
			sql.delete(sql.length() - 1, sql.length());
		}
		jt.update(sql.toString(), args.toArray());
	}

	public List<Lottery> downloadHistoryLotteryData() {

		return null;
	}

	public Map<String, Object> getMaxDateAndCount() {
		String sql = "select max(dt) maxDate,count(*) ct from t_shishicai";
		return jt.queryForMap(sql);
	}

	/**
	 * 获取最大日期那天的记录数
	 * @return
	 */
	public Map<String, Object> getMaxDateCountWithDate() {
		String sql = "select max(dt) maxDate,count(*) ct from t_shishicai group by dt desc limit 1";
		return jt.queryForMap(sql);
	}

}
